package com.changgou.search.controller;

import com.changgou.search.feign.SkuFeign;
import com.changgou.search.pojo.SkuInfo;
import entity.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
@RequestMapping("/search")
public class SkuController {
    @Autowired
    private SkuFeign skuFeign;

    /**
     * 搜索
     * @param searchMap
     * @return
     */
    @GetMapping(value = "/list")
    public String search(@RequestParam(required = false) Map<String,String> searchMap, Model model) throws Exception{
        //调用changgou-service-search微服务
        Map resultMap = skuFeign.search(searchMap);
        model.addAttribute("result",resultMap);
        //计算分页
        Page<SkuInfo> pageInfo=new Page<>(
                Long.parseLong(resultMap.get("total").toString()),
                Integer.parseInt(resultMap.get("pageNum").toString()),
                Integer.parseInt(resultMap.get("pageSize").toString())
        );

        model.addAttribute("pageInfo",pageInfo);
        //用于回显数据
        model.addAttribute("searchMap",searchMap);
        //填充请求地址
        String[] urls = url(searchMap);
        model.addAttribute("url",urls[0]);
        model.addAttribute("sorturl",urls[1]);
        return "search";
    }

    /**
     * 拼接用户点击后的请求地址
     * @param searchMap
     * @return
     */
    public String[] url(Map<String,String> searchMap){
        String url="/search/list";
        //用于排序的url
        String sorturl="/search/list";
        if(searchMap != null && searchMap.size() > 0){
            url+="?";
            sorturl+="?";
            for (Map.Entry<String, String> entry : searchMap.entrySet()) {
                String key= entry.getKey();
                //去掉分页参数
                if (key.equalsIgnoreCase("pageNum") ){
                    continue;
                }
                String value=entry.getValue();
                url+=key+"="+value+"&";
                //跳过排序参数
                if (key.equalsIgnoreCase("sortField") || key.equalsIgnoreCase("sortRule")){
                    continue;
                }
                sorturl+=key+"="+value+"&";
            }
            url=url.substring(0,url.length()-1);
            sorturl=sorturl.substring(0,sorturl.length()-1);
        }
        return new String[]{url,sorturl};
    }
}
